package org.foj.presenter {

import com.degrafa.paint.SolidFill;

import org.foj.components.PieChart;

import mx.collections.ArrayCollection;

import org.foj.components.PieChartSlice;
import org.foj.event.EventDispatcherFactory;
import org.foj.event.PieChartEvent;
import org.foj.model.PieChartModel;

public class PieChartPresenter {

    private var _view:PieChart;
    private var _model:PieChartModel;
    private var _id:String;
    private var _dataProvider:ArrayCollection;

    public function PieChartPresenter(view:PieChart, id:String) {
        this._view = view;
        this._model = new PieChartModel();
        this._id = id;

        EventDispatcherFactory.getEventDispatcher()
                .addEventListener(PieChartEvent.DATA_PROVIDER_UPDATED,
                refreshData);
    }

    private function refreshData(event:PieChartEvent = null):void {
        if (event.id == _id) {
            changeData(event.data);
        }
    }

    public function set dataProvider(data:ArrayCollection):void {
        _view.legendDataGrid.dataProvider = data;
        this._dataProvider = data;
    }

    public function get dataProvider():ArrayCollection {
        return this._dataProvider;
    }

    public function changeData(data:ArrayCollection):void
    {
        dataProvider = data;
        createSlices();
    }

    private function createSlices():void
    {
        while (dataProvider.length > _view.pieGroup.numChildren) {
            _view.pieGroup.addChild(new PieChartSlice());
        }
        setLegendColors();
        redrawSlices();
    }

    private function setLegendColors():void {
        for (var i:int = 0; i < dataProvider.length; i++)
        {
            dataProvider.getItemAt(i).legend = _model.getLegendColorForIndex(i);
        }
    }

    private function redrawSlices():void
    {
        var currentAngle:Number = 0;
        var totalUnits:Number = _model.getTotalUnits(_dataProvider);

        for (var i:int = 0; i < _view.pieGroup.numChildren; i++) {
            var slice:PieChartSlice = _view.pieGroup.getChildAt(i) as PieChartSlice;
            var legendColor:Number = _model.getLegendColorForIndex(i);
            var arc:Number = i < dataProvider.length ?
                    _model.getAngleForItem(dataProvider[i].units, totalUnits) : 0;
            // workaround for weird display if only one arc and it's 360 degrees
            arc = arc < 360 ? arc : 359.99;

            redrawSlice(slice, currentAngle, arc, legendColor);
            currentAngle += arc;
        }
        _view.pieGroup.draw(null, null);
    }

    private function redrawSlice(slice:PieChartSlice,
                                 startAngle:Number,
                                 arc:Number,
                                 color:Number):void {
        slice.arc.fill = new SolidFill(color, 1);
        slice.arc.startAngle = startAngle;
        slice.arc.arc = arc;
        slice.refresh();
    }

}
}